// 战斗管理器模块
(function (global) {
    class BattleManager {
        constructor(game) {
            this.game = game;
        }

        startNormalBattle() {
            const game = this.game;
            console.log('Starting normal battle');
            game.gameState = 'battle';
            game.battleTurn = 0;
            game.lastBattleGoldReward = 0;
            game.wasEliteBattle = false;
            game.wasBossBattle = false;
            game.player.startNewBattle();
            game.currentEnemies = this.generateEnemies();
            console.log('Enemies generated:', game.currentEnemies);
            game.showScreen('game-screen');
            game.player.energy = game.player.maxEnergy;
            while (game.playerHand.length > 0) {
                game.playerDiscardPile.push(game.playerHand.pop());
            }
            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'battleStart', floor: game.currentFloor, game }));
            }
            game.updatePlayerAvatar();
            game.drawHand();
            game.updateBattleDisplay();
            game.updateUI();
            this.showEnemyDialog();
            this.playBattleMusic();
        }

        startEliteBattle() {
            const game = this.game;
            game.gameState = 'battle';
            game.battleTurn = 0;
            game.lastBattleGoldReward = 0;
            game.wasEliteBattle = true;
            game.wasBossBattle = false;
            game.player.startNewBattle();
            game.currentEnemies = this.generateEliteEnemies();
            game.showScreen('game-screen');
            game.player.energy = game.player.maxEnergy;
            while (game.playerHand.length > 0) {
                game.playerDiscardPile.push(game.playerHand.pop());
            }
            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'battleStart', floor: game.currentFloor, game }));
            }
            game.updatePlayerAvatar();
            game.drawHand();
            game.updateBattleDisplay();
            game.updateUI();
            this.showEnemyDialog();
            this.playBattleMusic();
        }

        startBossBattle() {
            const game = this.game;
            game.gameState = 'battle';
            game.battleTurn = 0;
            game.lastBattleGoldReward = 0;
            game.wasEliteBattle = false;
            game.wasBossBattle = true;
            game.player.startNewBattle();
            game.currentEnemies = this.generateBossEnemies();
            game.showScreen('game-screen');
            game.player.energy = game.player.maxEnergy;
            while (game.playerHand.length > 0) {
                game.playerDiscardPile.push(game.playerHand.pop());
            }
            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'battleStart', floor: game.currentFloor, game }));
            }
            game.updatePlayerAvatar();
            game.drawHand();
            game.updateBattleDisplay();
            game.updateUI();
            this.showEnemyDialog();
            this.playBattleMusic();
        }

        playBattleMusic() {
            const battleMusic = document.getElementById('battle-music');
            if (battleMusic) {
                battleMusic.volume = 0.5;
                battleMusic.play().catch(error => {
                    console.log('音乐播放失败，可能需要用户交互:', error);
                });
            }
        }

        stopBattleMusic() {
            const battleMusic = document.getElementById('battle-music');
            if (battleMusic) {
                battleMusic.pause();
                battleMusic.currentTime = 0;
            }
        }

        generateEnemies() {
            const game = this.game;
            const enemyTypes = ['math_test', 'chinese_test', 'english_test', 'physics_test'];
            const selectedType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)];
            return [new Enemy(selectedType, game.currentFloor, false, false, game.difficultyTier)];
        }

        generateEliteEnemies() {
            const game = this.game;
            const eliteTypes = this.getEliteTypesForFloor(game.currentFloor);
            const selectedType = eliteTypes[Math.floor(Math.random() * eliteTypes.length)];
            return [new Enemy(selectedType, game.currentFloor, true, false, game.difficultyTier)];
        }

        generateBossEnemies() {
            const game = this.game;
            const bossTypes = ['gaokao_boss', 'interview_boss'];
            const selectedType = bossTypes[Math.floor(Math.random() * bossTypes.length)];
            return [new Enemy(selectedType, game.currentFloor, false, true, game.difficultyTier)];
        }

        getEliteTypesForFloor(floor) {
            if (floor === 4) return ['elite_math', 'elite_chinese'];
            if (floor === 8) return ['elite_english', 'elite_physics'];
            if (floor === 12) return ['elite_chemistry', 'elite_biology'];
            return [];
        }

        isEliteFloor(floor) {
            return floor === 4 || floor === 8 || floor === 12;
        }

        isBossFloor(floor) {
            return floor === 15;
        }

        useCard(card) {
            const game = this.game;
            if (!card) return;

            let actualCost = card.cost;
            if (game.playerRelics && game.playerRelics.some(r => r.name === '恶魔契约')) {
                actualCost = Math.max(0, card.cost - 2);
            }

            if (game.player.energy < actualCost) {
                this.showEnergyInsufficientWarning(card);
                game.addBattleLog(`⚠️ 能量不足！需要${actualCost}点能量，当前只有${game.player.energy}点`);
                return;
            }

            if (game.playerRelics && game.playerRelics.some(r => r.name === '恶魔契约')) {
                game.player.takeDamage(1);
                game.addBattleLog('恶魔契约：失去1点生命');
            }

            game.player.energy -= actualCost;
            game.addBattleLog(`使用卡牌: ${card.name} (消耗${actualCost}能量)`);

            this.executeCardEffect(card);

            game.currentTurnCardCount = (game.currentTurnCardCount || 0) + 1;
            if (card.type === 'attack') {
                game.currentTurnAttackCount = (game.currentTurnAttackCount || 0) + 1;
            }
            if (game.rhythmMasteryActive) {
                if (game.currentTurnCardCount % 3 === 0 && (game.rhythmTriggersThisTurn || 0) < 2) {
                    game.rhythmTriggersThisTurn = (game.rhythmTriggersThisTurn || 0) + 1;
                    game.player.addBlock(1);
                    this.queueDraw(1);
                    game.addBattleLog('节奏掌控触发：+1护甲，抽1张');
                }
            }

            if (card.name === '终结') {
                const index = game.playerHand.indexOf(card);
                if (index > -1) {
                    game.playerHand.splice(index, 1);
                    game.playerExhaustPile.push(card);
                    game.addBattleLog(`消耗: ${card.name}`);
                }
            } else {
                const cardIndex = game.playerHand.indexOf(card);
                if (cardIndex > -1) {
                    game.playerHand.splice(cardIndex, 1);
                    game.playerDiscardPile.push(card);
                    game.addBattleLog(`弃牌: ${card.name}`);
                }
            }

            if ((game.pendingDraw || 0) > 0) {
                this.drawCards(game.pendingDraw);
                game.pendingDraw = 0;
            }

            game.updateUI();
            game.updateHandDisplay();
            game.updateBattleDisplay();
        }

        executeCardEffect(card) {
            const game = this.game;
            const shouldDoubleCast = !!game.nextSpellDouble && card.isSpell && card.name !== '引导';
            if (shouldDoubleCast) {
                game.nextSpellDouble = false;
            }

            switch (card.type) {
                case 'attack':
                    if (card.name === '临界爆发') {
                        const handCount = game.playerHand.length;
                        if (handCount >= 6) {
                            this.dealDamageToAll(10);
                            game.addBattleLog('临界爆发：群体伤害10点');
                        } else {
                            let dmg = 14 + game.player.getSkillBonus();
                            if (game.player.energy === 0) {
                                dmg += 8;
                            }
                            this.dealDamage(dmg);
                            game.addBattleLog('临界爆发：单体伤害');
                        }
                        break;
                    }

                    if (card.name === '连携打击') {
                        let dmg = card.getDamage(game.player);
                        if ((game.currentTurnAttackCount || 0) >= 2) {
                            dmg += 6;
                            this.dealDamage(dmg);
                            this.queueDraw(1);
                            game.addBattleLog('连携打击：连携已激活，+6并抽1');
                        } else {
                            this.dealDamage(dmg);
                        }
                        break;
                    }

                    const damage = card.getDamage(game.player);
                    if (shouldDoubleCast) {
                        this.dealDamage(damage);
                        this.dealDamage(damage);
                        game.addBattleLog('引导：法术触发两次');
                    } else {
                        this.dealDamage(damage);
                    }

                    if (card.name === '火焰打击') {
                        if (game.player.strength >= 3) {
                            this.dealDamage(5);
                            game.addBattleLog('火焰打击触发额外效果！');
                        }
                    } else if (card.name === '元素重击') {
                        game.applyCardAttribute(card, 'strength', 1);
                        game.addBattleLog('获得1点力量');
                    } else if (card.name === '风刃') {
                        if (game.player.dexterity >= 3) {
                            this.queueDraw(1);
                            game.addBattleLog('风刃触发额外效果！');
                        }
                    } else {
                        this.executeSpellAttack(card);
                    }
                    break;
                case 'defend':
                    if (card.name === '魔法护盾') {
                        game.player.addBlock(card.getBlock(game.player));
                        game.applyCardAttribute(card, 'intelligence', 1);
                        game.addBattleLog('获得护甲和1点智力');
                    } else {
                        game.player.addBlock(card.getBlock(game.player));
                    }
                    break;
                case 'skill':
                    if (card.name === '引导') {
                        game.nextSpellDouble = true;
                        game.addBattleLog('引导：你的下一张法术牌将触发两次');
                    } else if (card.name === '破绽识别') {
                        const target = game.currentEnemies[0];
                        if (target && target.statusManager) {
                            target.statusManager.addStatus(new Status('易伤', 2, 1, '受到伤害增加'));
                            const hasWeak = target.statusManager.getStatusValue('虚弱') > 0;
                            const hasPoison = target.statusManager.getStatusValue('中毒') > 0;
                            if (hasWeak || hasPoison) {
                                target.statusManager.addStatus(new Status('易伤', 1, 1, '额外易伤'));
                            }
                            game.addBattleLog('破绽识别：施加易伤');
                            game.updateBattleDisplay();
                        }
                    } else if (card.name === '节奏掌控') {
                        game.rhythmMasteryActive = true;
                        game.rhythmTriggersThisTurn = 0;
                        game.addBattleLog('节奏掌控：每第3张牌触发奖励（最多2次）');
                    } else {
                        this.executeSkill(card);
                    }
                    if (game.playerRelics && game.playerRelics.length) {
                        game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'skillUsed', game }));
                    }
                    break;
                case 'energy':
                    game.player.energy += card.energy || 0;
                    game.addBattleLog(`获得${card.energy || 0}点能量`);
                    break;
                default:
                    game.addBattleLog(`使用卡牌: ${card.name}`);
                    break;
            }
        }

        executeSpellAttack(card) {
            const game = this.game;
            switch (card.name) {
                case '智慧之箭':
                    game.applyCardAttribute(card, 'intelligence', 1);
                    game.addBattleLog('智慧之箭：获得1点智力');
                    break;
                case '奥术飞弹':
                    this.queueDraw(1);
                    game.addBattleLog('奥术飞弹：抽1张牌');
                    break;
                case '智慧风暴':
                    game.applyCardAttribute(card, 'intelligence', 2);
                    game.addBattleLog('智慧风暴：获得2点智力');
                    break;
                case '知识爆炸':
                    this.queueDraw(2);
                    game.addBattleLog('知识爆炸：抽2张牌');
                    break;
                case '冰霜射击':
                    this.queueDraw(1);
                    game.addBattleLog('冰霜射击：抽1张牌');
                    break;
                case '闪电链':
                    game.applyCardAttribute(card, 'dexterity', 1);
                    game.addBattleLog('闪电链：获得1点敏捷');
                    break;
                default:
                    break;
            }
        }

        executeSkill(card) {
            const game = this.game;
            switch (card.name) {
                case '愤怒':
                    game.applyCardAttribute(card, 'strength', 2);
                    game.addBattleLog('获得2点力量');
                    break;
                case '坚韧':
                    game.player.addBlock(card.getBlock(game.player));
                    game.applyCardAttribute(card, 'strength', 1);
                    game.addBattleLog('获得护甲和力量');
                    break;
                case '狂暴':
                    game.applyCardAttribute(card, 'strength', 3);
                    game.player.takeDamage(1);
                    game.addBattleLog('获得3点力量，失去1点生命');
                    break;
                case '战吼':
                    game.applyCardAttribute(card, 'strength', 2);
                    this.queueDraw(1);
                    game.addBattleLog('获得2点力量，抽1张牌');
                    break;
                case '蛮力':
                    game.applyCardAttribute(card, 'strength', 1);
                    game.addBattleLog('获得1点力量');
                    break;
                case '不屈':
                    game.player.addBlock(card.getBlock(game.player));
                    if (game.player.health < game.player.maxHealth * 0.5) {
                        game.applyCardAttribute(card, 'strength', 2);
                        game.addBattleLog('获得护甲和额外力量');
                    } else {
                        game.addBattleLog('获得护甲');
                    }
                    break;
                case '终结':
                    game.addBattleLog('消耗所有能量');
                    break;
                case '敏捷':
                    game.applyCardAttribute(card, 'dexterity', 2);
                    game.addBattleLog('获得2点敏捷');
                    break;
                case '影分身':
                    game.applyCardAttribute(card, 'dexterity', 3);
                    this.queueDraw(2);
                    game.addBattleLog('获得3点敏捷，抽2张牌');
                    break;
                case '风之舞':
                    game.applyCardAttribute(card, 'dexterity', 1);
                    game.addBattleLog('获得1点敏捷');
                    break;
                case '瞬移':
                    game.applyCardAttribute(card, 'dexterity', 2);
                    game.addBattleLog('获得2点敏捷，本回合免疫伤害');
                    break;
                case '学习':
                    game.applyCardAttribute(card, 'intelligence', 1);
                    this.queueDraw(1);
                    game.addBattleLog('获得1点智力，抽1张牌');
                    break;
                case '成长':
                    if (card.upgraded) {
                        game.applyCardAttribute(card, 'strength', 2);
                        game.applyCardAttribute(card, 'dexterity', 2);
                        game.applyCardAttribute(card, 'intelligence', 2);
                        game.addBattleLog('成长（已升级）：获得2点所有属性');
                    } else {
                        game.applyCardAttribute(card, 'strength', 1);
                        game.applyCardAttribute(card, 'dexterity', 1);
                        game.applyCardAttribute(card, 'intelligence', 1);
                        game.addBattleLog('成长：获得1点所有属性');
                    }
                    break;
                case '专注':
                    game.applyCardAttribute(card, 'intelligence', 2);
                    this.queueDraw(1);
                    game.addBattleLog('获得2点智力，抽1张牌');
                    break;
                case '模仿':
                    game.addBattleLog('复制一张手牌');
                    break;
                case '创新':
                    game.applyCardAttribute(card, 'intelligence', 2);
                    this.queueDraw(2);
                    game.addBattleLog('获得2点智力，抽2张牌');
                    break;
                case '适应':
                    game.addBattleLog('根据当前状态获得属性');
                    break;
                case '突破':
                    game.applyCardAttribute(card, 'intelligence', 3);
                    this.queueDraw(3);
                    game.addBattleLog('获得3点智力，抽3张牌');
                    break;
                case '觉醒':
                    game.applyCardAttribute(card, 'strength', 5);
                    game.applyCardAttribute(card, 'dexterity', 5);
                    game.applyCardAttribute(card, 'intelligence', 5);
                    game.addBattleLog('获得5点所有属性');
                    break;
                case '魔法护盾':
                    game.player.addBlock(3);
                    game.applyCardAttribute(card, 'intelligence', 1);
                    game.addBattleLog('获得3点护甲和1点智力');
                    break;
                case '战意燃烧':
                    game.applyCardAttribute(card, 'strength', 1);
                    game.applyCardAttribute(card, 'intelligence', 1);
                    game.addBattleLog('获得1点力量和1点智力');
                    break;
                case '秘法步法':
                    game.applyCardAttribute(card, 'dexterity', 1);
                    game.applyCardAttribute(card, 'intelligence', 1);
                    game.addBattleLog('获得1点敏捷和1点智力');
                    break;
                case '奥术智慧':
                    game.applyCardAttribute(card, 'intelligence', 1);
                    this.queueDraw(1);
                    game.addBattleLog('获得1点智力，抽1张牌');
                    break;
                case '能量爆发':
                    game.player.energy += 2;
                    game.addBattleLog('获得2点能量');
                    break;
                case '冥想':
                    game.player.addBlock(card.getBlock(game.player));
                    game.player.energy += 1;
                    game.addBattleLog('获得护甲和1点能量');
                    break;
                case '活力':
                    game.player.energy += 3;
                    game.player.takeDamage(2);
                    game.addBattleLog('获得3点能量，失去2点生命');
                    break;
                case '充电':
                    game.player.energy += 1;
                    game.player.addBlock(3);
                    game.addBattleLog('获得1点能量和3点护甲');
                    break;
                case '香蕉':
                    game.player.addStrength(1, 'battle');
                    game.player.addDexterity(1, 'battle');
                    game.addBattleLog('获得1点力量和1点敏捷');
                    break;
                case '酒':
                    game.player.addStrength(2, 'battle');
                    game.player.takeDamage(3);
                    game.addBattleLog('获得2点力量，失去3点生命');
                    break;
                default:
                    game.addBattleLog(`使用技能: ${card.name}`);
                    break;
            }
        }

        dealDamage(damage) {
            const game = this.game;
            if (game.currentEnemies.length > 0) {
                const target = game.currentEnemies[0];
                if (!target) return;

                if (game.playerRelics && game.playerRelics.some(r => r.name === '诅咒之书')) {
                    damage = Math.floor(damage * 1.5);
                }

                const isCrit = damage >= 20;
                this.updateCombo();
                target.takeDamage(damage);
                game.addBattleLog(`对 ${target.name} 造成了 ${damage} 点伤害`);

                if (isCrit) {
                    this.playSound('crit');
                } else {
                    this.playSound('hit');
                }

                this.showDamageNumber(damage, target, isCrit);
                this.shakeEnemy(target);
                this.screenShake(damage);
                this.createHitParticles(target, isCrit);

                setTimeout(() => {
                    game.updateBattleDisplay();
                }, 100);

                if (target.health <= 0) {
                    setTimeout(() => {
                        this.defeatEnemy(target);
                    }, 300);
                }
            }
        }

        queueDraw(n = 1) {
            const game = this.game;
            game.pendingDraw = (game.pendingDraw || 0) + Math.max(0, n);
        }

        drawCards(n = 1) {
            const game = this.game;
            let drawn = 0;
            for (let i = 0; i < n; i++) {
                if (game.playerHand.length >= game.player.maxHandSize) {
                    break;
                }

                if (game.playerDeck.length === 0) {
                    if (game.playerDiscardPile.length > 0) {
                        game.playerDeck = [...game.playerDiscardPile];
                        game.playerDiscardPile = [];
                        game.shuffleDeck();
                    } else {
                        break;
                    }
                }

                const card = game.playerDeck.pop();
                game.addCardToHand(card);
                drawn++;
            }
            return drawn;
        }

        dealDamageToAll(damage) {
            const game = this.game;
            if (game.currentEnemies.length === 0) return;
            game.currentEnemies.slice().forEach(target => {
                target.takeDamage(damage);
                game.addBattleLog(`对 ${target.name} 造成了 ${damage} 点伤害`);
                if (target.health <= 0) {
                    setTimeout(() => this.defeatEnemy(target), 100);
                }
            });
            setTimeout(() => {
                game.updateBattleDisplay();
            }, 100);
        }

        playSound(soundName) {
            const soundMap = {
                'hit': 'hit-sound',
                'crit': 'crit-sound',
                'card': 'card-use-sound',
                'death': 'enemy-death-sound',
                'upgrade': 'card-upgrade-sound'
            };

            const soundId = soundMap[soundName];
            if (!soundId) return;

            const sound = document.getElementById(soundId);
            if (sound) {
                sound.currentTime = 0;
                sound.volume = 0.5;
                sound.play().catch(error => {
                    console.log(`音效播放失败: ${soundName}`, error);
                });
            }
        }

        updateCombo() {
            const game = this.game;
            const now = Date.now();
            if (now - game.lastAttackTime > game.comboTimeout) {
                game.comboCount = 0;
            }

            game.comboCount++;
            game.lastAttackTime = now;

            if (game.comboCount > 1) {
                this.showComboText();
            }
        }

        showComboText() {
            const enemyContainer = document.getElementById('enemy-container');
            if (!enemyContainer) return;

            const comboElement = document.createElement('div');
            const game = this.game;
            comboElement.className = 'combo-text';
            comboElement.textContent = `${game.comboCount} COMBO!`;

            const rect = enemyContainer.getBoundingClientRect();
            comboElement.style.left = `${rect.width / 2}px`;
            comboElement.style.top = '20px';
            comboElement.style.position = 'absolute';
            comboElement.style.transform = 'translateX(-50%)';

            enemyContainer.appendChild(comboElement);

            setTimeout(() => {
                if (comboElement.parentNode) {
                    comboElement.parentNode.removeChild(comboElement);
                }
            }, 1500);
        }

        showDamageNumber(damage, enemy, isCrit = false) {
            const enemyContainer = document.getElementById('enemy-container');
            if (!enemyContainer) return;

            const enemyElements = enemyContainer.querySelectorAll('.enemy');
            if (enemyElements.length === 0) {
                setTimeout(() => this.showDamageNumber(damage, enemy, isCrit), 100);
                return;
            }

            const enemyElement = enemyElements[0];
            const rect = enemyElement.getBoundingClientRect();
            const containerRect = enemyContainer.getBoundingClientRect();

            if (isCrit) {
                const critElement = document.createElement('div');
                critElement.className = 'crit-text';
                critElement.textContent = 'CRIT!';

                const x = rect.left - containerRect.left + rect.width / 2;
                const y = rect.top - containerRect.top + rect.height / 2 - 30;

                critElement.style.left = `${x}px`;
                critElement.style.top = `${y}px`;
                critElement.style.position = 'absolute';
                critElement.style.transform = 'translate(-50%, -50%)';

                enemyContainer.appendChild(critElement);

                setTimeout(() => {
                    if (critElement.parentNode) {
                        critElement.parentNode.removeChild(critElement);
                    }
                }, 800);
            }

            const damageElement = document.createElement('div');
            damageElement.className = 'damage-number';
            damageElement.textContent = `-${damage}`;

            if (damage >= 20 || isCrit) {
                damageElement.style.color = '#ff0000';
                damageElement.style.fontSize = '2.5rem';
                damageElement.style.textShadow = '2px 2px 6px rgba(0, 0, 0, 0.9), 0 0 15px #ff0000';
                damageElement.classList.add('crit-damage');
            } else if (damage >= 10) {
                damageElement.style.color = '#ff6600';
                damageElement.style.fontSize = '2.2rem';
            }

            const x = rect.left - containerRect.left + rect.width / 2;
            const y = rect.top - containerRect.top + rect.height / 2;

            damageElement.style.left = `${x}px`;
            damageElement.style.top = `${y}px`;
            damageElement.style.position = 'absolute';
            damageElement.style.transform = 'translate(-50%, -50%)';

            enemyContainer.appendChild(damageElement);

            setTimeout(() => {
                if (damageElement.parentNode) {
                    damageElement.parentNode.removeChild(damageElement);
                }
            }, 1000);
        }

        createHitParticles(enemy, isCrit = false) {
            const enemyContainer = document.getElementById('enemy-container');
            if (!enemyContainer) return;

            const enemyElements = enemyContainer.querySelectorAll('.enemy');
            if (enemyElements.length === 0) return;

            const enemyElement = enemyElements[0];
            const rect = enemyElement.getBoundingClientRect();
            const containerRect = enemyContainer.getBoundingClientRect();

            const centerX = rect.left - containerRect.left + rect.width / 2;
            const centerY = rect.top - containerRect.top + rect.height / 2;

            const particleCount = isCrit ? 15 : 8;

            for (let i = 0; i < particleCount; i++) {
                const particle = document.createElement('div');
                particle.className = 'hit-particle';
                if (isCrit) {
                    particle.classList.add('crit-particle');
                }

                const angle = (Math.PI * 2 * i) / particleCount + (Math.random() - 0.5) * 0.5;
                const speed = isCrit ? 80 + Math.random() * 40 : 50 + Math.random() * 30;
                const distance = speed * 0.5;

                const endX = Math.cos(angle) * distance;
                const endY = Math.sin(angle) * distance;

                particle.style.left = `${centerX}px`;
                particle.style.top = `${centerY}px`;
                particle.style.position = 'absolute';
                particle.style.setProperty('--end-x', `${endX}px`);
                particle.style.setProperty('--end-y', `${endY}px`);

                enemyContainer.appendChild(particle);

                setTimeout(() => {
                    if (particle.parentNode) {
                        particle.parentNode.removeChild(particle);
                    }
                }, 500);
            }
        }

        shakeEnemy(enemy) {
            const enemyContainer = document.getElementById('enemy-container');
            if (!enemyContainer) return;

            const enemyElements = enemyContainer.querySelectorAll('.enemy');
            if (enemyElements.length === 0) return;

            const enemyElement = enemyElements[0];
            enemyElement.classList.add('enemy-flash');
            setTimeout(() => {
                enemyElement.classList.remove('enemy-flash');
            }, 200);

            enemyElement.classList.add('enemy-hit');
            setTimeout(() => {
                enemyElement.classList.remove('enemy-hit');
            }, 300);
        }

        screenShake(damage) {
            const intensity = Math.min(damage / 20, 1);
            if (intensity < 0.1) return;

            const gameScreen = document.getElementById('game-screen');
            if (!gameScreen) return;

            gameScreen.classList.add('screen-shake');
            setTimeout(() => {
                gameScreen.classList.remove('screen-shake');
            }, 500);
        }

        defeatEnemy(enemy) {
            const game = this.game;
            this.playSound('death');
            game.comboCount = 0;
            game.addBattleLog(`击败了 ${enemy.name}`);
            game.lastBattleGoldReward = enemy.goldReward || 0;
            game.playerGold += game.lastBattleGoldReward;
            game.currentEnemies = game.currentEnemies.filter(e => e !== enemy);

            if (game.currentEnemies.length === 0) {
                this.battleVictory();
            }
        }

        battleVictory() {
            const game = this.game;
            console.log('战斗胜利，显示结果界面');

            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'battleEnd', floor: game.currentFloor, game }));
            }

            this.organizeDeck();

            game.gameState = 'victory';
            game.showScreen('battle-result');
            this.displayRewards();
            if (game.wasEliteBattle) {
                game.elitesDefeated = (game.elitesDefeated || 0) + 1;
            }
            if (game.wasBossBattle) {
                game.bossDefeated = (game.bossDefeated || 0) + 1;
            }
            game.wasBossBattle = false;
            game.wasEliteBattle = false;
            game.saveRunHistory({ outcome: 'victory' });

            this.stopBattleMusic();
            this.bindContinueButton();
        }

        organizeDeck() {
            const game = this.game;
            while (game.playerHand.length > 0) {
                game.playerDiscardPile.push(game.playerHand.pop());
            }

            if (game.playerDiscardPile.length > 0) {
                game.playerDeck = [...game.playerDeck, ...game.playerDiscardPile];
                game.playerDiscardPile = [];
                game.shuffleDeck();
            }

            game.addBattleLog('战斗结束，牌堆已整理');
        }

        bindContinueButton() {
            const game = this.game;
            const continueBtn = document.getElementById('continue-adventure');
            if (continueBtn) {
                const newBtn = continueBtn.cloneNode(true);
                continueBtn.parentNode.replaceChild(newBtn, continueBtn);
                newBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('继续冒险按钮被点击');
                    game.continueAdventure();
                });
                console.log('继续冒险按钮事件已绑定');
            } else {
                console.error('未找到继续冒险按钮');
            }
        }

        displayRewards() {
            const game = this.game;
            const rewardsContainer = document.getElementById('rewards');
            const cardRewards = this.generateCardRewards();
            const battleGoldReward = game.lastBattleGoldReward || 0;

            let droppedRelics = [];
            if (game.wasEliteBattle) {
                const allRelics = relicDatabase.getAllRelics();
                const shuffled = [...allRelics].sort(() => 0.5 - Math.random());
                droppedRelics = shuffled.slice(0, 3);
            }
            game.droppedRelicRewards = droppedRelics;

            const droppedPotion = Math.random() < 0.5 ? this.getRandomPotion() : null;
            game.droppedPotionReward = droppedPotion;

            const cardHtml = cardRewards.map((card, idx) => {
                const rarityClass = `rarity-${card.rarity || 'common'}`;
                const roleClass = `card-role-${game.getCardRole(card)}`;
                return `
                <div class="deck-card reward-card ${rarityClass} ${roleClass}" data-reward-index="${idx}" style="cursor: pointer; transition: transform 0.2s;">
                    ${game.renderCardContent(card, { mode: 'preview' })}
                </div>
            `;
            }).join('');

            let relicHtml = '';
            if (droppedRelics.length > 0) {
                relicHtml = '<div class="reward-item"><span>遗物奖励（三选一）：</span></div>';
                relicHtml += '<div class="reward-relic-list" style="display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; margin-bottom: 10px;">';
                droppedRelics.forEach((relic, idx) => {
                    const rarityClass = `rarity-${relic.rarity || 'common'}`;
                    relicHtml += `
                    <div class="deck-card reward-relic ${rarityClass}" data-relic-index="${idx}" style="cursor: pointer; transition: transform 0.2s; min-width: 150px;">
                        <div class="deck-card-name">${relic.name}</div>
                        <div class="deck-card-description">${relic.description}</div>
                    </div>
                `;
                });
                relicHtml += '</div>';
            }

            const potionHtml = droppedPotion ? `
            <div class="reward-item">
                <span>药水: <span id="potion-reward-display" class="potion-clickable" style="cursor: pointer; color: #4ecdc4; font-weight: bold; text-decoration: underline;">${droppedPotion.name}</span> (点击获取)</span>
            </div>
        ` : '';

            rewardsContainer.innerHTML = `
            <div class="reward-item">
                <span>金币: <span id="gold-reward-display" class="gold-clickable" style="cursor: pointer; color: #ffd700; font-weight: bold; text-decoration: underline;">+${battleGoldReward}</span> (点击获取)</span>
            </div>
            ${relicHtml}
            ${potionHtml}
            <div class="reward-item"><span>卡牌奖励（可选其一或跳过）：</span></div>
            <div class="reward-card-list" style="display: flex; gap: 10px; flex-wrap: wrap; justify-content: center;">${cardHtml}</div>
            <div class="reward-actions" style="margin-top: 10px;">
                <button id="skip-card-reward" class="btn-secondary">跳过</button>
            </div>
        `;

            const goldDisplay = document.getElementById('gold-reward-display');
            if (goldDisplay && battleGoldReward > 0) {
                goldDisplay.addEventListener('click', () => {
                    this.claimGoldReward(goldDisplay, battleGoldReward);
                });
            }

            const relicElements = rewardsContainer.querySelectorAll('.reward-relic');
            relicElements.forEach((elem, idx) => {
                elem.addEventListener('click', () => {
                    if (!elem.classList.contains('disabled')) {
                        this.claimRelicReward(droppedRelics[idx], elem);
                    }
                });
                elem.addEventListener('mouseenter', () => {
                    if (!elem.classList.contains('disabled')) {
                        elem.style.transform = 'scale(1.05)';
                    }
                });
                elem.addEventListener('mouseleave', () => {
                    elem.style.transform = 'scale(1)';
                });
            });

            const potionDisplay = document.getElementById('potion-reward-display');
            if (potionDisplay && droppedPotion) {
                potionDisplay.addEventListener('click', () => {
                    this.claimPotionReward(potionDisplay, droppedPotion);
                });
            }

            const cardElems = rewardsContainer.querySelectorAll('.reward-card');
            cardElems.forEach((elem, idx) => {
                elem.addEventListener('click', () => {
                    if (!elem.classList.contains('disabled')) {
                        this.claimCardReward(cardRewards[idx], elem);
                    }
                });
                elem.addEventListener('mouseenter', () => {
                    if (!elem.classList.contains('disabled')) {
                        elem.style.transform = 'scale(1.05)';
                    }
                });
                elem.addEventListener('mouseleave', () => {
                    elem.style.transform = 'scale(1)';
                });
            });

            const skipBtn = document.getElementById('skip-card-reward');
            if (skipBtn) {
                skipBtn.addEventListener('click', () => this.skipCardReward());
            }

            game.currentCardRewards = cardRewards;
        }

        claimGoldReward(element, amount) {
            if (element.classList.contains('claimed')) return;
            element.classList.add('claimed');
            element.style.animation = 'goldPulse 0.5s ease-out';

            const game = this.game;
            game.addBattleLog(`获得 ${amount} 金币`);

            setTimeout(() => {
                const rewardItem = element.closest('.reward-item');
                if (rewardItem) {
                    rewardItem.style.transition = 'opacity 0.3s ease-out';
                    rewardItem.style.opacity = '0';
                    setTimeout(() => {
                        rewardItem.style.display = 'none';
                    }, 300);
                }
            }, 500);
        }

        claimRelicReward(relic, element) {
            const game = this.game;
            if (!relic || !game.droppedRelicRewards || game.droppedRelicRewards.length === 0) return;
            if (element.classList.contains('disabled')) return;

            document.querySelectorAll('.reward-relic').forEach(el => {
                el.classList.add('disabled');
                el.style.cursor = 'not-allowed';
            });

            game.playerRelics.push(relic);
            element.classList.add('claimed');
            element.style.animation = 'goldPulse 0.5s ease-out';

            game.addBattleLog(`获得遗物: ${relic.name}`);
            game.updateRelicsDisplay();
            game.updateMapRelicsDisplay();

            setTimeout(() => {
                document.querySelectorAll('.reward-relic').forEach(el => {
                    if (el !== element) {
                        el.style.transition = 'opacity 0.3s ease-out';
                        el.style.opacity = '0';
                        setTimeout(() => {
                            el.style.display = 'none';
                        }, 300);
                    }
                });
            }, 500);

            game.droppedRelicRewards = [];
        }

        claimPotionReward(element, potion) {
            const game = this.game;
            if (!potion || !game.droppedPotionReward) return;
            if (element.classList.contains('claimed')) return;

            game.playerPotions.push(potion);
            game.droppedPotionReward = null;

            element.classList.add('claimed');
            element.style.animation = 'potionPulse 0.5s ease-out';

            game.addBattleLog(`获得药水: ${potion.name}`);
            game.updatePotionsDisplay();
            game.updateMapPotionsDisplay();

            setTimeout(() => {
                const rewardItem = element.closest('.reward-item');
                if (rewardItem) {
                    rewardItem.style.transition = 'opacity 0.3s ease-out';
                    rewardItem.style.opacity = '0';
                    setTimeout(() => {
                        rewardItem.style.display = 'none';
                    }, 300);
                }
            }, 500);
        }

        generateCardRewards() {
            const game = this.game;
            const characterType = game.selectedCharacter;
            const db = cardDatabase;

            const rollRarity = () => {
                const r = Math.random();
                if (game.currentFloor && game.currentFloor <= 4) {
                    if (r < 0.35) return 'common';
                    if (r < 0.80) return 'uncommon';
                    return 'rare';
                } else {
                    if (r < 0.5) return 'common';
                    if (r < 0.85) return 'uncommon';
                    return 'rare';
                }
            };

            const picks = [];
            for (let i = 0; i < 3; i++) {
                let rarity = rollRarity();
                let pool = [
                    ...db.getCharacterCardsByRarity(characterType, rarity),
                    ...db.getCommonCardsByRarity(rarity)
                ];
                if (pool.length === 0 && rarity === 'rare') {
                    rarity = 'uncommon';
                    pool = [
                        ...db.getCharacterCardsByRarity(characterType, rarity),
                        ...db.getCommonCardsByRarity(rarity)
                    ];
                }
                if (pool.length === 0 && rarity === 'uncommon') {
                    rarity = 'common';
                    pool = [
                        ...db.getCharacterCardsByRarity(characterType, rarity),
                        ...db.getCommonCardsByRarity(rarity)
                    ];
                }
                if (pool.length === 0) {
                    pool = db.getCommonCards();
                }
                const base = pool[Math.floor(Math.random() * pool.length)];
                const newCard = new Card(
                    base.name,
                    base.cost,
                    base.type,
                    base.value,
                    base.description,
                    base.effects || [],
                    base.isSpell || false,
                    base.rarity || rarity || 'common',
                    base.role || null
                );
                if (Math.random() < 0.5) {
                    newCard.upgrade();
                }
                picks.push(newCard);
            }
            return picks;
        }

        claimCardReward(card, element) {
            if (!card) return;
            const game = this.game;

            const rewardedCard = new Card(
                card.name,
                card.cost,
                card.type,
                card.value,
                card.description,
                card.effects || [],
                card.isSpell || false,
                card.rarity || 'common',
                card.role || null
            );
            rewardedCard.upgraded = card.upgraded || false;

            game.playerDeck.push(rewardedCard);
            game.addBattleLog(`获得卡牌: ${rewardedCard.name} (已加入卡牌包)`);

            const rewardsContainer = document.getElementById('rewards');
            const list = rewardsContainer ? rewardsContainer.querySelector('.reward-card-list') : null;
            if (list) {
                const allCards = Array.from(list.querySelectorAll('.reward-card'));
                allCards.forEach(cardEl => {
                    cardEl.classList.add('disabled');
                    cardEl.style.cursor = 'not-allowed';
                    if (cardEl === element) {
                        cardEl.style.animation = 'cardClaim 0.5s ease-out';
                    }
                    setTimeout(() => {
                        cardEl.style.transition = 'opacity 0.3s ease-out';
                        cardEl.style.opacity = '0';
                        setTimeout(() => { cardEl.style.display = 'none'; }, 300);
                    }, 500);
                });
            }

            if (rewardsContainer) {
                const skipBtn = document.getElementById('skip-card-reward');
                if (skipBtn) {
                    skipBtn.style.transition = 'opacity 0.3s ease-out';
                    skipBtn.style.opacity = '0';
                    setTimeout(() => { skipBtn.style.display = 'none'; }, 300);
                }
                const rewardItems = rewardsContainer.querySelectorAll('.reward-item');
                rewardItems.forEach(item => {
                    if (item.textContent.includes('卡牌奖励')) {
                        item.style.transition = 'opacity 0.3s ease-out';
                        item.style.opacity = '0';
                        setTimeout(() => { item.style.display = 'none'; }, 300);
                    }
                });
            }
        }

        skipCardReward() {
            const game = this.game;
            game.addBattleLog('跳过了卡牌奖励');
            const rewardsContainer = document.getElementById('rewards');
            if (rewardsContainer) {
                const list = rewardsContainer.querySelector('.reward-card-list');
                if (list) {
                    list.querySelectorAll('.reward-card').forEach(el => {
                        el.classList.add('disabled');
                        el.style.transition = 'opacity 0.3s ease-out';
                        el.style.opacity = '0';
                        setTimeout(() => {
                            el.style.display = 'none';
                        }, 300);
                    });
                }
                setTimeout(() => {
                    const skipBtn = document.getElementById('skip-card-reward');
                    if (skipBtn) {
                        skipBtn.style.transition = 'opacity 0.3s ease-out';
                        skipBtn.style.opacity = '0';
                        setTimeout(() => {
                            skipBtn.style.display = 'none';
                        }, 300);
                    }
                    const rewardItems = rewardsContainer.querySelectorAll('.reward-item');
                    rewardItems.forEach(item => {
                        if (item.textContent.includes('卡牌奖励')) {
                            item.style.transition = 'opacity 0.3s ease-out';
                            item.style.opacity = '0';
                            setTimeout(() => {
                                item.style.display = 'none';
                            }, 300);
                        }
                    });
                }, 300);
            }
        }

        getRandomPotion() {
            const potions = [
                { name: '777感冒灵', description: '恢复15点生命值' },
                { name: '糖水', description: '获得2点能量' },
                { name: '可乐', description: '获得1点能量，抽1张牌' },
                { name: '香蕉', description: '获得1点力量和1点敏捷' },
                { name: '酒', description: '获得2点力量，失去3点生命' }
            ];
            return potions[Math.floor(Math.random() * potions.length)];
        }

        endTurn() {
            const game = this.game;
            game.battleTurn++;
            game.totalBattleTurns = (game.totalBattleTurns || 0) + 1;
            game.addBattleLog(`=== 第 ${game.battleTurn} 回合结束 ===`);

            this.enemyTurn();

            if (game.player.statusManager) {
                game.player.statusManager.processTurnEnd();
            }

            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'turnEnd', floor: game.currentFloor, game }));
            }

            game.currentEnemies.forEach(enemy => {
                if (enemy.statusManager) {
                    enemy.processTurnEnd();
                }
            });

            game.player.startNewTurn();
            game.player.energy = game.player.maxEnergy;
            game.player.block = 0;

            while (game.playerHand.length > 0) {
                game.playerDiscardPile.push(game.playerHand.pop());
            }
            game.addBattleLog('手牌进入弃牌堆');

            if (game.playerRelics && game.playerRelics.length) {
                game.playerRelics.forEach(r => RelicEffectProcessor.processRelic(r, game.player, { phase: 'turnStart', floor: game.currentFloor, game }));
            }
            game.currentTurnCardCount = 0;
            game.currentTurnAttackCount = 0;
            game.rhythmTriggersThisTurn = 0;
            game.nextSpellDouble = false;
            game.rhythmMasteryActive = false;
            game.pendingDraw = 0;
            game.drawHand();

            game.addBattleLog(`=== 第 ${game.battleTurn + 1} 回合开始 ===`);
            game.updateUI();
            game.updateBattleDisplay();
        }

        enemyTurn() {
            const game = this.game;
            game.currentEnemies.forEach(enemy => {
                if (enemy.health > 0) {
                    const oldHealth = game.player.health;
                    enemy.act(game.player);
                    const damage = oldHealth - game.player.health;
                    if (damage > 0) {
                        game.addBattleLog(`${enemy.name} 对玩家造成了 ${damage} 点伤害`);
                        this.showPlayerHurt(damage);
                    }
                }
            });

            if (game.player.health <= 0) {
                game.gameOver();
            }
        }

        showEnemyDialog() {
            const game = this.game;
            if (game.currentEnemies.length === 0) return;
            const enemy = game.currentEnemies[0];
            const dialog = this.getEnemyDialog(enemy.type, enemy.isElite, enemy.isBoss);
            if (dialog) {
                setTimeout(() => {
                    game.addBattleLog(`💬 ${enemy.name}: "${dialog}"`);
                }, 500);
            }
        }

        getEnemyDialog(type, isElite, isBoss) {
            const dialogs = {
                'math_test': ['数学题不会做的，都是基础不扎实！', '这道题我见过，你猜对了吗？', '计算要仔细，一步错步步错！'],
                'chinese_test': ['古文理解，看的是文化底蕴。', '作文要写得好，先要读得多。', '字词句段篇，缺一不可。'],
                'english_test': ['English requires practice every day!', 'Vocabulary is the foundation!', 'Grammar matters!'],
                'physics_test': ['物理重在理解，不是死记硬背。', '公式要活用，不能生搬硬套。', '实验原理要搞清楚。'],
                'chemistry_test': ['化学方程式要配平！', '元素周期表要熟记！', '实验操作要规范！'],
                'biology_test': ['生物结构要理解透彻。', '实验观察要仔细。', '知识要系统化。'],
                'history_test': ['历史是时间的见证。', '史实要准确，不能混淆。', '理解历史背景很重要。'],
                'geography_test': ['地理要结合地图理解。', '气候地形要综合分析。', '区域特征要掌握。'],
                'elite_math': ['竞赛题可不是普通题目！', '数学思维要灵活！', '这道题需要创新思路！'],
                'elite_chinese': ['作文大赛，文采很重要！', '立意深刻才能得高分！', '文笔要优美流畅！'],
                'elite_english': ['英语演讲，口语是关键！', '发音要标准，语调要自然！', '内容要有深度！'],
                'elite_physics': ['物理竞赛，需要创新思维！', '理论要扎实，实验要精准！', '这道题考验综合能力！'],
                'elite_chemistry': ['化学竞赛，动手能力很重要！', '实验设计要科学！', '分析要全面深入！'],
                'elite_biology': ['生物竞赛，观察能力要强！', '实验要严谨，数据要准确！', '知识面要广！'],
                'gaokao_boss': ['高考，决定你人生的重要时刻！', '准备好了吗？这是真正的考验！', '全力以赴，不留遗憾！'],
                'interview_boss': ['面试看的是综合素质。', '你的能力够强吗？', '职场可不是学校。']
            };
            const pool = dialogs[type] || ['准备好了吗？'];
            return pool[Math.floor(Math.random() * pool.length)];
        }

        showPlayerHurt(damage) {
            this.playSound('hit');

            const playerAvatar = document.getElementById('battle-player-avatar');
            if (playerAvatar) {
                playerAvatar.classList.add('player-hurt');
                setTimeout(() => {
                    playerAvatar.classList.remove('player-hurt');
                }, 300);
            }

            const playerArea = document.querySelector('.player-area');
            if (playerArea) {
                const damageElement = document.createElement('div');
                damageElement.className = 'damage-number player-damage';
                damageElement.textContent = `-${damage}`;
                damageElement.style.color = '#ff6666';
                damageElement.style.position = 'absolute';
                damageElement.style.left = '50%';
                damageElement.style.top = '20%';
                damageElement.style.transform = 'translateX(-50%)';
                playerArea.appendChild(damageElement);

                setTimeout(() => {
                    if (damageElement.parentNode) {
                        damageElement.parentNode.removeChild(damageElement);
                    }
                }, 1000);
            }

            const gameScreen = document.getElementById('game-screen');
            if (gameScreen) {
                gameScreen.classList.add('screen-shake-light');
                setTimeout(() => {
                    gameScreen.classList.remove('screen-shake-light');
                }, 300);
            }
        }

        animateCardUse(cardElement) {
            if (!cardElement) return;
            cardElement.classList.add('card-using');
            setTimeout(() => {
                if (cardElement.parentNode) {
                    cardElement.classList.remove('card-using');
                }
            }, 400);
        }

        showEnergyInsufficientWarning(card) {
            const game = this.game;
            const energyElement = document.getElementById('player-energy');
            if (energyElement) {
                energyElement.classList.add('energy-insufficient');
                setTimeout(() => {
                    energyElement.classList.remove('energy-insufficient');
                }, 1500);
            }

            const handContainer = document.getElementById('player-hand');
            if (handContainer) {
                const cardElements = handContainer.querySelectorAll('.card');
                cardElements.forEach(element => {
                    const cardName = element.querySelector('.card-name')?.textContent;
                    if (cardName === card.name) {
                        element.classList.add('card-insufficient-energy');
                        setTimeout(() => {
                            element.classList.remove('card-insufficient-energy');
                        }, 800);
                    }
                });
            }
        }

        updatePlayerStatusDisplay() {
            const game = this.game;
            const playerStatusContainer = document.getElementById('player-status');
            if (!playerStatusContainer) return;

            playerStatusContainer.innerHTML = '';

            if (game.player) {
                const displayStatuses = [];

                if (game.player.strength > 0) {
                    displayStatuses.push({ name: '力量', value: game.player.strength, icon: '💪' });
                }
                if (game.player.dexterity > 0) {
                    displayStatuses.push({ name: '敏捷', value: game.player.dexterity, icon: '⚡' });
                }
                if (game.player.intelligence > 0) {
                    displayStatuses.push({ name: '智力', value: game.player.intelligence, icon: '🧠' });
                }
                if (game.player.block > 0) {
                    displayStatuses.push({ name: '护甲', value: game.player.block, icon: '🛡️' });
                }

                if (game.player.statusManager) {
                    game.player.statusManager.getAllStatuses().forEach(status => {
                        displayStatuses.push({
                            name: status.name,
                            value: status.value,
                            stacks: status.stacks,
                            icon: status.getIcon(),
                            duration: status.duration,
                            description: status.description
                        });
                    });
                }

                displayStatuses.forEach(status => {
                    const statusElement = document.createElement('div');
                    statusElement.className = 'status-badge buff-positive';
                    statusElement.title = `${status.name}${status.value ? ': ' + status.value : ''}${status.duration ? ' (' + status.duration + '回合)' : ''}`;
                    statusElement.innerHTML = `<span class="status-icon">${status.icon}</span><span class="status-text">${status.name}${status.stacks > 1 ? ' ' + status.stacks : ''}</span>`;
                    playerStatusContainer.appendChild(statusElement);
                });

                if (displayStatuses.length === 0) {
                    const emptyElement = document.createElement('span');
                    emptyElement.textContent = '无';
                    emptyElement.style.cssText = 'color: #999; font-style: italic;';
                    playerStatusContainer.appendChild(emptyElement);
                }
            }
        }

        renderStatusDisplay(statuses) {
            if (!statuses || statuses.length === 0) return '';

            let statusHtml = '<div class="enemy-status-container">';
            statuses.forEach(status => {
                const icon = status.getIcon();
                const duration = status.duration > 0 ? `(${status.duration})` : '';
                statusHtml += `
                <span class="status-badge ${status.getColorClass()}" title="${status.description || status.name}">
                    <span class="status-icon">${icon}</span>
                    <span class="status-text">${status.name} ${duration}</span>
                </span>
            `;
            });
            statusHtml += '</div>';
            return statusHtml;
        }

        showPotionSelection() {
            const game = this.game;
            if (game.playerPotions.length === 0) {
                game.addBattleLog('没有可用的药水！');
                return;
            }

            const potionMenu = document.createElement('div');
            potionMenu.className = 'potion-menu';
            potionMenu.innerHTML = `
            <div class="potion-menu-content">
                <h3>选择药水</h3>
                <div class="potion-list">
                    ${game.playerPotions.map((potion, index) => `
                        <div class="potion-item" onclick="game.usePotion(${index})">
                            <div class="potion-name">${potion.name}</div>
                            <div class="potion-description">${potion.description}</div>
                        </div>
                    `).join('')}
                </div>
                <button onclick="game.closePotionMenu()">取消</button>
            </div>
        `;

            potionMenu.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;

            document.body.appendChild(potionMenu);
        }

        usePotion(index) {
            const game = this.game;
            if (index >= 0 && index < game.playerPotions.length) {
                const potion = game.playerPotions[index];
                this.executePotionEffect(potion);
                game.playerPotions.splice(index, 1);
                game.addBattleLog(`使用药水: ${potion.name}`);
                this.closePotionMenu();
            }
        }

        executePotionEffect(potion) {
            const game = this.game;
            switch (potion.name) {
                case '777感冒灵':
                    game.player.health = Math.min(game.player.maxHealth, game.player.health + 15);
                    game.addBattleLog('恢复15点生命值');
                    break;
                case '糖水':
                    game.player.energy += 2;
                    game.addBattleLog('获得2点能量');
                    break;
                case '可乐':
                    game.player.energy += 1;
                    const drawn = this.drawCards(1);
                    if (drawn > 0) {
                        game.updateHandDisplay();
                    }
                    game.addBattleLog('获得1点能量，抽1张牌');
                    break;
                case '香蕉':
                    game.player.addStrength(1, 'battle');
                    game.player.addDexterity(1, 'battle');
                    game.addBattleLog('获得1点力量和1点敏捷');
                    break;
                case '酒':
                    game.player.addStrength(2, 'battle');
                    game.player.takeDamage(3);
                    game.addBattleLog('获得2点力量，失去3点生命');
                    break;
                default:
                    game.addBattleLog(`使用药水: ${potion.name}`);
                    break;
            }
            game.updateUI();
            game.updateBattleDisplay();
        }

        closePotionMenu() {
            const potionMenu = document.querySelector('.potion-menu');
            if (potionMenu) {
                potionMenu.remove();
            }
        }
    }

    global.BattleManager = BattleManager;
})(window);
